<?php declare(strict_types=1);

namespace App\Http\Middleware;

use App\Lib\Error\ErrorConstant;
use http\Client\Response;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Swoft\Bean\Annotation\Mapping\Bean;
use Swoft\Context\Context;
use Swoft\Http\Message\ContentType;
use Swoft\Http\Server\Contract\MiddlewareInterface;
use Swoft\Http\Session\HttpSession;

/**
 * @Bean("CorsMiddleware")
 */
class CorsMiddleware implements MiddlewareInterface
{
    /**
     * Process an incoming server request.
     *
     * @param ServerRequestInterface $request
     * @param RequestHandlerInterface $handler
     *
     * @return ResponseInterface
     * @inheritdoc
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        if(config('service.safeguard', 2) == 1 && strtolower(getTenant()) <> 'admin'){
            return $this->configResponse(context()->getResponse()->withContentType(ContentType::JSON)->withData([
                'status'=>ErrorConstant::STATE_ERROR,
                'error_code'=> 7000,
                'message'=> '系统维护中，请稍后再试！'
            ]));
        }

        $sess = HttpSession::current();
        $sess->set('__SWOFT_SESSION_ID__', 'SWOFT_SESSION_ID');//修复sessoion bug

        if ('OPTIONS' === strtoupper($request->getMethod())) {
            $response = Context::mustGet()->getResponse();
            return $this->configResponse($response);
        }

        $ret = $handler->handle($request);

        $data = $ret->getData()??[];
        if (is_object($data) || is_array($data)) {
            return $this->configResponse(context()->getResponse()->withContentType(ContentType::JSON)->withData($data));
        }
        return $this->configResponse(context()->getResponse()->withContentType(ContentType::HTML)->withContent($data));
    }

    private function configResponse(ResponseInterface $response)
    {
        return $response
            ->withHeader('Access-Control-Allow-Origin', '*')
            ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
            ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
    }
}
